PHP Tutorial
PHP function is a piece of code that can be reused many times. It can take input as argument list and return value.
Advantage of PHP functions are code reusability, less code and easy to understand.
PHP provides us with two major types of functions:
A function will not execute automatically when a page loads and function will executed by a call to the function.
function functionName() {
code to be executed;
}
A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
Let's put these syntax into real use.
Following is the example showing how to create a function.
<?php
function codealways() {
echo "Code Always To Become Best Programmer.";
}
codealways(); // call the function
?>
This will produce the following result −
Code Always To Become Best Programmer.
PHP gives you option to pass your parameters inside a function.
You can pass as many as parameters your like.
function functionName($variable, $variable..$variable)
{
code to be executed;
}
Let's put these syntax into real use.
Following is the example showing how to create a function with parameters.
<?php
function codealways($message) {
echo "Code Always $message";
}
// call the function
codealways("To Become Best Programmer.");
?>
This will produce the following result −
Code Always To Become Best Programmer.
To let a function return a value, use the return statement.
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "10 + 10 = " . sum(10, 10) . "<br>";
echo "20 + 20 = " . sum(20, 20) . "<br>";
echo "30 + 30 = " . sum(30, 30);
?>
This will produce the following result −
10 + 10 = 20
20 + 20 = 40
30 + 30 = 60